package com.zhuliwei.handler.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhuliwei.domain.entity.LoginUser;
import com.zhuliwei.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mp表字段自动填充
 *
 * @author 朱力维
 * @time 2022/10/20 18:50
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private String userId = null;

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            userId = loginUser.getUser().getId();
        } catch (Exception e) {
            e.printStackTrace();
            userId = "system";//表示是自己创建
        }
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            userId = "system";//表示是自己创建
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }
}